<?php

namespace app\job;

/**
 * 同步商品队列
 */

use app\admin\model\Config;
use app\model\DistributionSetting;
use app\model\Goods;
use app\model\GoodsInfo;
use app\model\GoodsSync;
use app\model\GoodsType;
use app\model\Shop;
use app\model\User;
use app\service\GoodsService;
use libs\Redis;
use think\facade\Log;
use think\queue\Job;
use util\Logger;

class SyncGoodsJob
{
    public function fire(Job $job, $data)
    {
        Log::init([
            'type'        => 'file',
            'apart_level' => ['error'],
            'level'       => ['error'],
            'path'        => app()->getRootPath() . "runtime/log/queue/",
            'max_files'   => 15,
        ]);
        $type        = $data['type'];
        $next_key    = '';
        $sum         = 0;
        $setting     = DistributionSetting::getLevelInfo(1, 1);
        $share_ratio = $setting['ratio'] ?? 0;
        try {
            do {
                [$save, $shop_save, $info_save, $next_key, $goods_num] = GoodsService::getGoodsList($type, $share_ratio, $next_key);
                $sum += $goods_num;
                if ($save) {
                    (new Goods())->saveAll($save);
                }
                if ($shop_save) {
                    (new Shop())->saveAll($shop_save);
                }
                if ($info_save) {
                    (new GoodsInfo())->saveAll($info_save);
                }
                var_dump('已处理商品数：' . $sum);

            } while ($next_key);
            var_dump('总商品数：' . $sum);
            GoodsSync::where('type', $type)->update(['status' => 1]);
            $job->delete();
        } catch (\Exception $e) {
            GoodsSync::where('type', $type)->update(['status' => 1]);
            $job->delete();
            Logger::error('同步商品队列失败', [
                'data' => $data,
                'msg'  => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}
